<template>
  <!-- 项目的最外层 -->
  <div class="outer">
    <!-- 注册内容 -->
    <div class="register">
      <h3>
        注册新用户
        <span class="go"
          >我有账号，去 <router-link to="/login">登陆</router-link>
        </span>
      </h3>
      <ValidationObserver v-slot="{ handleSubmit }">
        <form @submit.prevent="handleSubmit(onSubmit)">
          <ValidationProvider
            class="content"
            rules="phoneRequired|phoneNumber"
            v-slot="{ errors }"
          >
            <label>手机号:</label>
            <input
              type="text"
              placeholder="请输入你的手机号"
              v-model="user.phone"
            />
            <span class="error-msg">{{ errors[0] }}</span>
          </ValidationProvider>
          <ValidationProvider
            class="content"
            rules="codeRequired|codeNumber"
            v-slot="{ errors }"
            tag="div"
            mode="lazy"
          >
            <label>验证码:</label>
            <input type="text" placeholder="请输入验证码" v-model="user.code" />
            <input
              type="button"
              value="获取验证码"
              :disabled="isSend"
              style="width: 90px"
              @click="getCode"
            />
            <span class="error-msg">{{ errors[0] }}</span>
          </ValidationProvider>
          <ValidationProvider
            class="content"
            rules="passRequired|passNumber"
            v-slot="{ errors }"
            tag="div"
            mode="lazy"
          >
            <label>登录密码:</label>
            <input
              type="text"
              placeholder="请输入你的登录密码"
              v-model="user.password"
            />
            <span class="error-msg">{{ errors[0] }}</span>
          </ValidationProvider>
          <ValidationProvider
            class="content"
            :rules="`passRequired|passNumber|rePassNumber:${user.password}|`"
            v-slot="{ errors }"
            tag="div"
            mode="lazy"
          >
            <label>确认密码:</label>
            <input
              type="text"
              placeholder="请输入确认密码"
              v-model="user.rePassword"
            />
            <span class="error-msg">{{ errors[0] }}</span>
          </ValidationProvider>
          <ValidationProvider
            class="controls"
            rules="isShow"
            v-slot="{ errors }"
            tag="div"
            mode="lazy"
          >
            <input name="m1" type="checkbox" v-model="user.isShow" />
            <span>同意协议并注册《尚品汇用户协议》</span>
            <span class="error-msg">{{ errors[0] }}</span>
          </ValidationProvider>
          <div class="btn">
            <button>完成注册</button>
          </div>
        </form>
      </ValidationObserver>
    </div>
    <!-- 底部 -->
    <div class="copyright">
      <ul>
        <li>关于我们</li>
        <li>联系我们</li>
        <li>联系客服</li>
        <li>商家入驻</li>
        <li>营销中心</li>
        <li>手机尚品汇</li>
        <li>销售联盟</li>
        <li>尚品汇社区</li>
      </ul>
      <div class="address">地址：北京市xxxxxxxxxxxxxxxxx</div>
      <div class="beian">京ICP备19006430号</div>
    </div>
  </div>
</template>

<script>
import { ValidationObserver, ValidationProvider, extend } from "vee-validate";

import { required } from "vee-validate/dist/rules";
import { phoneNumberReg, passwordReg, codeNumbReg } from "@/utils/reg.js";
import { getVerificationCode, reqRegistration } from "@/api/index";

// 验证手机号，必填
extend("phoneRequired", {
  // extend是用来定义验证规则的，里面有两个参数 第1个参数是规则名称 第2个是规则
  ...required,
  message: "手机号不能为空,请输入...",
});
//验证手机格式
extend("phoneNumber", {
  // 自己写校验规则 返回true表示校验成功 false表示失败
  validate(val) {
    // val表示要验证的数据
    return phoneNumberReg.test(val);
  },
  message: "手机号码格式不正确,请重新输入...",
});

// 验证验证码，必填
extend("codeRequired", {
  ...required,
  message: "请输入验证码",
});
// 验证码格式
extend("codeNumber", {
  // 自己写校验规则 返回true表示校验成功 false表示失败
  validate(val) {
    // val表示要验证的数据
    return codeNumbReg.test(val);
  },
  message: "验证码格式不正确",
});

// 验证密码，必填
extend("passNumber", {
  ...required,
  message: "密码不能为空,请输入...",
});
// 密码内容验证
extend("passRequired", {
  validate(val) {
    return passwordReg.test(val);
  },
  message: "密码格式不正确",
});

// 重复密码验证,两次是否一致
extend("rePassNumber", {
  // val 是原值，password是传进来的值
  validate(val, { password }) {
    return val === password;
  },
  message: "两次密码不一致",
  params: ["password"],
});

// 是否同意协议
extend("isShow", {
  validate(val) {
    return val;
  },
  message: "请勾选用户协议",
});

export default {
  name: "Home",
  data() {
    return {
      user: {
        phone: "", // 手机号
        password: "", // 密码
        rePassword: "", // 确认密码
        code: "", // 验证码
        isShow: false, // 是否同意
      },
      isSend: false, // 是否发送了验证码
    };
  },
  components: {
    ValidationObserver,
    ValidationProvider,
  },
  /* 
  给每一个输入框双向数据绑定,用来获取数据
  使用vee-validate插件进行表单效验,验证必填以及对各项数据的内容验证，内容验证要自己写正则
  获取验证码，发送请求携带手机号，需先判断手机号，将返回的验证码填入页面
  发送请求之后，禁用按钮，避免多次发送请求,可以加个定时器作倒计时
  表单提交，请求参数：phone | password | code  请求前判断参数，成功跳转登录页面
  */
  methods: {
    async getCode(e) {
      if (!phoneNumberReg.test(this.user.phone))
        return alert("请输入正确的手机号");
      let num = 60;
      this.isSend = true;
      this.timerId = setInterval(() => {
        num--;
        if (num == 0) {
          clearInterval(this.timerId);
          e.target.value = "获取验证码";
          this.isSend = false;
        }
        e.target.value = num + "秒后重新获取";
      }, 1000);
      const result = await getVerificationCode(this.user.phone);

      if (result.code === 200) {
        this.user.code = result.data;
      } else {
        alert("注册失败");
      }
    },
    async onSubmit() {
      const { phone, password, code } = this.user;
      if (!phone || !password || !code) return;
      console.log(phone, password, code);
      const result = await reqRegistration({ phone, password, code });
      if (result.code === 200) {
        this.$message({
          message: "注册成功",
          type: "success",
        });
        this.$router.push("/login");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.register {
  width: 1200px;
  height: 445px;
  border: 1px solid rgb(223, 223, 223);
  margin: 0 auto;

  h3 {
    background: #ececec;
    margin: 0;
    padding: 6px 15px;
    color: #333;
    border-bottom: 1px solid #dfdfdf;
    font-size: 20.04px;
    line-height: 30.06px;

    span {
      font-size: 14px;
      float: right;

      a {
        color: #e1251b;
      }
    }
  }

  div:nth-of-type(1) {
    margin-top: 40px;
  }

  .content {
    padding-left: 390px;
    margin-bottom: 18px;
    position: relative;

    label {
      font-size: 14px;
      width: 96px;
      text-align: right;
      display: inline-block;
    }

    input {
      width: 270px;
      height: 38px;
      padding-left: 8px;
      box-sizing: border-box;
      margin-left: 5px;
      outline: none;
      border: 1px solid #999;
    }

    img {
      vertical-align: sub;
    }

    .error-msg {
      position: absolute;
      top: 100%;
      left: 495px;
      color: red;
    }
  }

  .controls {
    text-align: center;
    position: relative;

    input {
      vertical-align: middle;
    }

    .error-msg {
      position: absolute;
      top: 100%;
      left: 495px;
      color: red;
    }
  }

  .btn {
    text-align: center;
    line-height: 36px;
    margin: 17px 0 0 55px;

    button {
      outline: none;
      width: 270px;
      height: 36px;
      background: #e1251b;
      color: #fff !important;
      display: inline-block;
      font-size: 16px;
    }
  }
}

.copyright {
  width: 1200px;
  margin: 0 auto;
  text-align: center;
  line-height: 24px;

  ul {
    li {
      display: inline-block;
      border-right: 1px solid #e4e4e4;
      padding: 0 20px;
      margin: 15px 0;
    }
  }
}
</style>